from .base import BASE_DIR, DEBUG

import os
import sys
import logging
from colorama import Fore, Back, Style, init  # pip install colorama

# 初始化colorama（Windows必需）
init(autoreset=True)

# 日志配置
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            '()': 'django.utils.log.ServerFormatter',
            'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
            'style': '{',
        },
        'colored_console': {
            '()': 'django.utils.log.ServerFormatter',
            'format': '%(levelname)s [%(asctime)s] %(message)s',
            'style': '%',
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'colored_console' if DEBUG else 'verbose',
            'stream': sys.stdout,
        },
        'error_file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'logs/error.log'),
            'maxBytes': 1024 * 1024,  # 1MB
            'backupCount': 1,
            'level': 'ERROR',
            'formatter': 'verbose',
        },
        'general_file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'logs/logger.log'),
            'maxBytes': 1024 * 1024,  # 1MB
            'backupCount': 1,
            'formatter': 'verbose',
        },
    },
    'loggers': {
        '': {  # root logger
            'handlers': ['console', 'error_file', 'general_file'] if not DEBUG else ['console'],
            'level': 'INFO',
            'propagate': False,
        },
        'django': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}

# 添加彩色日志格式化（在settings.py末尾添加）
if DEBUG:
    from django.utils.log import DEFAULT_LOGGING

    class ColorFormatter(logging.Formatter):
        LEVEL_COLORS = {
            'DEBUG': Fore.GREEN,
            'INFO': Fore.BLUE,
            'WARNING': Fore.YELLOW,
            'ERROR': Fore.RED,
            'CRITICAL': Fore.WHITE + Back.RED,
        }

        def format(self, record):
            levelname = record.levelname
            color = self.LEVEL_COLORS.get(levelname, '')
            record.levelname = f'{color}{levelname}{Style.RESET_ALL}'
            return super().format(record)

    LOGGING['formatters']['colored_console']['()'] = ColorFormatter
    LOGGING['handlers']['console']['formatter'] = 'colored_console'

# 创建日志目录
LOG_DIR = os.path.join(BASE_DIR, 'logs')
if not os.path.exists(LOG_DIR):
    try:
        os.makedirs(LOG_DIR, exist_ok=True)
    except OSError as e:
        logging.error(f'创建日志目录失败: {str(e)}')
